/*
 * @Author: xiehangyun 
 * @Date: 2025-05-15 10:47:05 
 * @Last Modified by: 肖思汗
 * @Last Modified time: 2025-08-05 15:15:03
 */

import { Address, Checkbox, Input, TextArea } from "@nutui/nutui-react-taro"; // 添加 Divider 导入
import { View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { autorun } from "mobx";
import { ReactNode, useEffect, useState } from "react";
import CustomHeader from "src/components/CustomHeader/CustomHeader";
import { ReceiveAddress } from "types/type";
import addressManageApi from "../AddressManage/addressManageApi";
import addressManageStore from "../AddressManage/addressManageStore";
import BottomBtns from "./BottomBtns/BottomBtns";
// import chinaJSON from "./china.json";
import styles from "./newAddressManage.module.less";
import newAddressManageApi from "./newAddressManageApi";

interface Iprops {
    children?: ReactNode
}

// 新建收货地址
export default function NewAddressManage() {

    const { appAddressId } = Taro.getCurrentInstance().router?.params || {};

    const [formData, setFormData] = useState<Omit<ReceiveAddress, "appAddressId">>({
        userName: "",           // 收货人姓名
        postalCode: "",         // 邮编
        province: "",  // 省
        city: "",               // 市
        county: "",             // 区
        detail: "",             // 详细地址
        nationalCode: "86",       // 国家码
        phone: "",              // 手机号码
        ifDefault: false          // 是否默认地址
    });
    const [showAddressPicker, setShowAddressPicker] = useState(false);


    // 初始化区域数据
    const [areaList, setAreaList] = useState<any>([]);

    const convertAreaData = (data: Array<any>) => {
        return data.map((item: any) => ({
            code: item.id,
            value: item.name,
            text: item.name,
            children: item.children ? convertAreaData(item.children) : []
        }));
    }



    useEffect(() => {

        newAddressManageApi.queryAreaTree().then((data: any) => {
            setAreaList(convertAreaData(data));
        });

        // 是否要回显
        if (appAddressId) {
            addressManageApi.getById(appAddressId).then((receiveAddress: ReceiveAddress) => {
                console.log("receiveAddress", receiveAddress);
                setFormData(receiveAddress);
            });
        } else {
            // setFormData({
            //     addressId: 0,           // 地址id
            //     userName: "",           // 收货人姓名
            //     postalCode: "000000",         // 邮编
            //     province: "",  // 省
            //     city: "",               // 市
            //     county: "",             // 区
            //     detail: "",             // 详细地址
            //     nationalCode: "",       // 国家码
            //     phone: "",              // 手机号码
            //     ifDefault: true          // 是否默认地址
            // });
        }
    }, []);

    const handleInputChange = (key: string, value: string) => {
        setFormData({ ...formData, [key]: value });
    };

    const handleCheckboxChange = (checked: boolean) => {
        setFormData({ ...formData, ifDefault: checked });
    };

    const handleSubmit = () => {
        const phoneRegex = /^1[3-9]\d{9}$/; // 简单的手机号码正则校验
        if (
            !formData.userName ||
            // !formData.postalCode ||
            !formData.province ||
            // !formData.city ||
            // !formData.county ||
            !formData.detail ||
            // !formData.nationalCode ||
            !formData.phone
        ) { // 添加街道校验
            Taro.showToast({
                title: '请填写完整的表单信息',
                icon: 'none',
                duration: 2000
            });
            return;
        }
        if (!phoneRegex.test(formData.phone)) {
            Taro.showToast({
                title: '请输入有效的手机号码',
                icon: 'none',
                duration: 2000
            });
            return;
        }
        console.log("提交表单数据:", formData);

        // 在这里可以添加表单验证和提交逻辑
        const {
            userName, postalCode, province, city, county, detail, nationalCode, phone, ifDefault
        } = formData;
        if (appAddressId) {
            addressManageStore.updata({
                appAddressId: Number(appAddressId),
                userName, postalCode, province, city, county, detail, nationalCode, phone, ifDefault
            }).then(() => {
                Taro.showToast({
                    title: '保存成功',
                    icon: 'none',
                    duration: 1000
                });
                Taro.navigateBack();
            });
        } else {
            addressManageStore.add({
                userName, postalCode, province, city, county, detail, nationalCode, phone, ifDefault
            }).then(() => {
                Taro.showToast({
                    title: '保存成功',
                    icon: 'none',
                    duration: 1000
                });
                Taro.navigateBack();
            });
        }

    };

    const handleAddressConfirm = (address: Array<string>) => {
        console.log(address);
        // setSelectedAddress(address);
        setFormData({
            ...formData,
            province: address[0],  // 省
            city: address[1],               // 市
            county: address[2],             // 区
        });
        // setShowAddressPicker(false);
    };

    useEffect(() => {
    }, []);

    useEffect(() => autorun(() => {
    }, { delay: 30 }), []);


    return (
        <View className={styles.newAddressManage}>

            {/* 自定义头部 */}
            <CustomHeader showBack />

            <View className={styles.from} >

                <View className={styles.formItem}>
                    <Input
                        placeholder="请输入收货人姓名"
                        value={formData.userName}
                        onChange={(value) => handleInputChange("userName", value)}
                    />
                </View>
                <View className={styles.formItem}>
                    <Input
                        placeholder="请输入联系电话"
                        value={formData.phone}
                        onChange={(value) => handleInputChange("phone", value)}
                    />
                </View>
                <View className={styles.formItem}>
                    <Input
                        placeholder="请选择省市区"
                        value={`${formData.province || ""}${formData.city || ""}${formData.county || ""}`}
                        onClick={() => setShowAddressPicker(true)}
                        // onClick={() => {
                        //     Taro.chooseContact({
                        //         success: (res) => {
                        //             console.log(res);
                        //         }
                        //     });
                        // }}
                        readOnly
                    />
                </View>
                <View className={styles.formItem}>
                    <TextArea
                        placeholder="请输入街道信息"
                        value={formData.detail}
                        className={styles.street}
                        onChange={(value) => handleInputChange("detail", value)} // 更新街道信息
                    />
                </View>
                <View className={`${styles.formItem} ${styles.checkboxContainer}`}>
                    <Checkbox
                        checked={formData.ifDefault}
                        onChange={(checked) => handleCheckboxChange(checked)}
                    >
                        设为默认地址
                    </Checkbox>
                </View>
                <Address
                    visible={showAddressPicker}
                    options={areaList}
                    onClose={() => setShowAddressPicker(false)}
                    onChange={(address: Array<string>) => handleAddressConfirm(address)}
                />
            </View>

            {/* 底部按钮 */}
            <BottomBtns save={handleSubmit} />
        </View>
    );
}

